﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CE.Job;
using CE.User;

public partial class user_profile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("login.aspx");
        }
        if (!Page.IsPostBack)
        {
            divAppForm.Visible = true;
            divMessage.Visible = false;

            usrDOB.StartYear = DateTime.Now.Year - 60;
            usrDOB.EndYear = DateTime.Now.Year - 15;

            if (Session[CE.Global.General.UserId] != null)
            {
                Profile _profile = new Profile();
                ProfileDB _profiledb = new ProfileDB();
                Int64 _uid = Int64.Parse(Session[CE.Global.General.UserId].ToString());
                _profile = _profiledb.GetProfile(_uid);
                ddlTitle.SelectedValue = _profile.Salutation;
                txtFullName.Text = _profile.Name;
                txtContactNumber.Text = _profile.ContactNumber;
                usrDOB.Day = _profile.DOB.Day;
                usrDOB.Month = _profile.DOB.Month;
                usrDOB.Year = _profile.DOB.Year;
                txtQualification.Text = _profile.Qualification;
                ddlExpYear.SelectedValue = _profile.YearsExperience;
                ddlSaleExp.SelectedValue = _profile.SalesExperience;
                ddlEmpStatus.SelectedValue = _profile.EmploymentStatus;
                txtOccupation.Text = _profile.Occupation;
                ddlCountry.SelectedValue = _profile.PreferredCountry;

                if (_profile.AttachCV != "")
                {
                    if (System.IO.File.Exists(_profile.AttachCV))
                    {
                        hidCV.Value = _profile.AttachCV;
                        lblUploadNew.Visible = true;
                    }
                    else
                    {
                        btnDownloadCV.Width = System.Web.UI.WebControls.Unit.Parse("180");
                        btnDownloadCV.Text = "Upload your latest CV now";
                        btnDownloadCV.Enabled = false;
                    }
                }
                else
                {
                    btnDownloadCV.Width = System.Web.UI.WebControls.Unit.Parse("180");
                    btnDownloadCV.Text = "Upload your latest CV now";
                    btnDownloadCV.Enabled = false;
                }

                if (_profile.VoiceRecord != "")
                {
                    aRecord.HRef += "?file=" + _profile.VoiceRecord;
                }
            }
        }
    }


    protected void btnSubmitForm_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (Session[CE.Global.General.UserId] != null)
            {
                try
                {
                    Account _useraccount = new Account();
                    AccountDB _useraccountdb = new AccountDB();

                    Profile _userprofile = new Profile();
                    ProfileDB _userprofiledb = new ProfileDB();

                    Application _application = new Application();
                    ApplicationDB _applicationdb = new ApplicationDB();

                    long _result = -1;

                    Int64 _uid = Int64.Parse(Session[CE.Global.General.UserId].ToString());
                    _useraccount = _useraccountdb.GetAccount(_uid);

                    _userprofile = _userprofiledb.GetProfile(_uid);

                    string _uploadFilePath = _userprofile.AttachCV;
                    if (fupCV.HasFile)
                    {
                        /***delete old cv***/
                        if (System.IO.File.Exists(_userprofile.AttachCV))
                            System.IO.File.Delete(_userprofile.AttachCV);

                        UploadFile(out _uploadFilePath, _uid);
                    }

                    _userprofile.Salutation = ddlTitle.SelectedItem.Text;
                    _userprofile.Name = Server.HtmlEncode(txtFullName.Text.Trim());
                    _userprofile.ContactNumber = Server.HtmlEncode(txtContactNumber.Text.Trim());
                    _userprofile.DOB = usrDOB.GetDate();
                    _userprofile.Qualification = Server.HtmlEncode(txtQualification.Text.Trim());
                    _userprofile.YearsExperience = ddlExpYear.SelectedItem.Text;
                    _userprofile.SalesExperience = ddlSaleExp.SelectedItem.Text;
                    _userprofile.EmploymentStatus = ddlEmpStatus.SelectedItem.Text;
                    _userprofile.Occupation = txtOccupation.Text;
                    _userprofile.PreferredCountry = ddlCountry.SelectedValue;
                    _userprofile.AttachCV = _uploadFilePath;

                    if (Session["ConfirmLastFileName"] != null)
                    {
                        string _tempFilePath = Session["ConfirmLastFileName"].ToString();
                        Session["ConfirmLastFileName"] = null;

                        string _webUrl = string.Empty;
                        string _filePath = GetFilePath(out _webUrl);
                        string _guidString = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8);
                        string _fileName = "Voice_user" + _uid.ToString() + "_" + _guidString + ".wav";
                        if (_userprofile.VoiceRecord != "")
                        {
                            string[] _splitfilename = _userprofile.VoiceRecord.Split('\\');
                            _fileName = _splitfilename[_splitfilename.Length - 1];
                        }

                        string fileName = _filePath + _fileName;

                        if (System.IO.File.Exists(fileName))
                        {
                            System.IO.File.Delete(fileName);
                        }
                        System.IO.File.Move(_tempFilePath, fileName);

                        _userprofile.VoiceRecord = fileName;
                    }

                    _result = _userprofiledb.Insert(_userprofile);

                    if (_result > 0)
                    {
                        Response.Redirect("profile.aspx");
                    }

                }
                catch (Exception Ex)
                {
                    divMessage.Visible = true;
                    lblMessage.Text = "Error found! Please try it later again.<br/>" + Ex.Message;
                    lblMessage.Font.Bold = true;
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                Response.Redirect("login.aspx");
            }
        }
    }

    private bool UploadFile(out string filePath, Int64 uid)
    {
        bool _retValue = false;

        filePath = string.Empty;

        try
        {
            TDS.IO.FileSystem _newFile = new TDS.IO.FileSystem();
            if (fupCV.HasFile)
            {
                HttpPostedFile _postFile = fupCV.PostedFile;

                int _fileLen = 0;

                if (_postFile.ContentLength > 0)
                {
                    _fileLen = _postFile.ContentLength / 1024;
                }

                string _fileName = _postFile.FileName;
                string _fileExt = System.IO.Path.GetExtension(_fileName).ToLower();
                bool _fileExtValid = false;

                string[] _arrFileExt = System.Configuration.ConfigurationManager.AppSettings["TDSJ.CVUploadFileExt"].Split(',');
                int _fileSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TDSJ.CVUploadFileSizeKB"]);

                for (int i = 0; i < _arrFileExt.Length; i++)
                {
                    if (_fileExt == _arrFileExt[i])
                    {
                        _fileExtValid = true;
                        break;
                    }
                }

                if (_fileExtValid)
                {
                    if (_fileLen > 0 && _fileLen <= _fileSize)
                    {
                        //string _filePath = AppDomain.CurrentDomain.BaseDirectory + "TDSCVUploadFiles\\";
                        string _filePath = AppDomain.CurrentDomain.BaseDirectory + "user\\";
                        //string _filePath = System.Configuration.ConfigurationManager.AppSettings["TDSJ.CVUploadFilePath"];
                        if (_newFile.CheckDirectory(_filePath))
                        {
                            //string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                            //if (!_newFile.CheckDirectory(_filePath + _curMonth))
                            //{
                            //    if (_newFile.CreateDirectory(_filePath, _curMonth))
                            //    {
                            //        _filePath += _curMonth + "\\";
                            //    }
                            //}
                            //else
                            //{
                            //    _filePath += _curMonth + "\\";
                            //}

                            //string _curDate = DateTime.Now.ToString("ddMMMyyyy");

                            //if (!_newFile.CheckDirectory(_filePath + _curDate))
                            //{
                            //    if (_newFile.CreateDirectory(_filePath, _curDate))
                            //    {
                            //        _filePath += _curDate + "\\";
                            //    }
                            //}
                            //else
                            //{
                            //    _filePath += _curDate + "\\";
                            //}

                            //filePath = _filePath + "JobApp_" + DateTime.Now.ToString("ddMMMyyyy_hhmmss_tt") + _fileExt;

                            //fupCV.SaveAs(filePath);

                            //_retValue = true;
                            ////_newFile.WriteNewFile(_filePath, _fileName, strException);
                            //_newFile = null;

                            string _curResumePath = "resume";

                            if (!_newFile.CheckDirectory(_filePath + _curResumePath))
                            {
                                if (_newFile.CreateDirectory(_filePath, _curResumePath))
                                {
                                    _filePath += _curResumePath + "\\";
                                }
                            }
                            else
                            {
                                _filePath += _curResumePath + "\\";
                            }

                            filePath = _filePath + "CV_" + uid.ToString() + "_" + DateTime.Now.ToString("ddMMMyyyy_hhmmss_tt") + _fileExt;

                            fupCV.SaveAs(filePath);

                            _retValue = true;
                            //_newFile.WriteNewFile(_filePath, _fileName, strException);
                            _newFile = null;
                        }
                    }
                    else
                    {
                        lblUploadMessage.Text = "<br/>Invalid or File size is over limit.";
                    }
                }
                else
                {
                    lblUploadMessage.Text = "<br/>Invalid file type.";
                }
            }
            //else
            //{
            //    //Mobile Device
            //    _retValue = !rfvCV.Enabled;
            //}
        }
        catch (Exception Ex)
        {
            lblUploadMessage.Text = "<br/>" + Ex.Message;
        }

        return _retValue;
    }
    protected void btnDownloadCV_Click(object sender, EventArgs e)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(hidCV.Value);
        if (!file.Exists)
        {
            Response.StatusCode = 500;
            Response.End();
            return;
        }
        Response.Clear();
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.MinValue);
        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.WriteFile(file.FullName);
        ApplicationInstance.CompleteRequest();
        Response.End();
    }
    private string GetFilePath(out string webUrl)
    {
        string _filePath = Server.MapPath("~\\voice-recording\\upload\\");
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        webUrl = "~/voice-recording/upload/";

        string _file = "Store";
        if (!_myIO.CheckDirectory(_filePath + _file))
        {
            if (_myIO.CreateDirectory(_filePath, _file))
            {
                _filePath += _file + "\\";
                webUrl += _file + "/";
            }
        }
        else
        {
            _filePath += _file + "\\";
            webUrl += _file + "/";
        }

        return _filePath;
    }
}